package com.example.tests;

import static org.junit.Assert.*;
import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.example.pages.InternalPage;
import com.example.pages.LoginPage;
import com.example.pages.UserPage;

import ru.esteru.selenium.factory.WebDriverFactory;


public class changeEmailTest {
	private WebDriver driver;
	private WebDriverWait wait;
	private String baseUrl;
	private StringBuffer verificationErrors = new StringBuffer();
	private LoginPage loginPage;
	private InternalPage somePage;
	private UserPage UserPage;
	
	
	@Before
	public void setUp() throws Exception {
		driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
		wait = new WebDriverWait(driver, 10);
		baseUrl = "http://localhost/";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}


	@Test
	public void ChangeEmail() {
		goToMainPage();
		logInAs("admin", "admin");
		goToUserProfile ();
		changeEmail("admin@admin.ru");
		assertTrue(isOnMyProfilePage());
		logOut();	
	}
	
	

	private void assertTrue(Object onMyProfilePage) {
		// TODO Auto-generated method stub
		
	}


	private void changeEmail(String email) {
		UserPage.NewEmailField.clear();
		UserPage.NewEmailField.sendKeys(email);
		UserPage.saveButton.click();
	}


	private Object isOnMyProfilePage() 
	{
	return somePage.menuProfileLink.isSelected();
	}

		
	private void goToUserProfile() {
		//go to User profile
		somePage.menuProfileLink.click();
	}

	private void logOut() {
		//logout
		somePage.menuLogOutLink.click();
		wait.until(alertIsPresent()).accept();	
	}

	private void logInAs(String username, String password) {
		//login as
		loginPage.userNameField.clear();
		loginPage.userNameField.sendKeys(username);
		loginPage.passwordField.clear();
		loginPage.passwordField.sendKeys(password);
		loginPage.loginButton.click();
	}

	private void goToMainPage() {
		//go to main page
		driver.get(baseUrl + "/php4dvd/");
		loginPage = PageFactory.initElements(driver, LoginPage.class);
		somePage = PageFactory.initElements(driver, InternalPage.class);
		UserPage = PageFactory.initElements(driver, UserPage.class);
	}

	
	
	@After
	public void tearDown() throws Exception {
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

}
